package com.bazaaroid.mobile.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpConnection;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.commons.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.bazaaroid.mobile.android.adapter.ImageAdapter;
import com.bazaaroid.mobile.android.db.DbBazaaAdapter;
import com.bazaaroid.mobile.db.model.partner.Product;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import android.view.View;

public class CategoryView extends Activity {

	private String TAG = "[CategoryView]";
	DbBazaaAdapter dbBazaaAdapter;
	
	public CategoryView() {
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    //setContentView(R.layout.basic_categories);
	    setContentView(R.layout.basic_categories_with_search);	
	    
	    try {
			dbBazaaAdapter = new DbBazaaAdapter(this);
			dbBazaaAdapter.initDatabase();
		
		    
		    /*
		     * Display category grid
		     */
		    GridView gridview = (GridView) findViewById(R.id.categoryview);
		    gridview.setAdapter(new ImageAdapter(this));
		    //gridview.setColumnWidth(gridview.getWidth() / 3);
	
		    gridview.setOnItemClickListener(
		    	new OnItemClickListener() 
			    {
			        public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
			        {
			            //Toast.makeText(CategoryView.this, "" + position, Toast.LENGTH_SHORT).show();
			        	
			        	// Categories
			        	// 1
			        }
			    }
		    );

		    /*
		     * Calling the search action
		     */
		    Intent intent = getIntent();
	        if(Intent.ACTION_SEARCH.equals(intent.getAction()))
	        {
	        	String query = intent.getStringExtra(SearchManager.QUERY);
	        	doSearchAction(query);
	        }
	        
	        // If we want to start the search right away with click on any local key...
	        setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
	        
	        
	        /*EditText et = (EditText)findViewById(R.id.bazaaroid_search_box);
	        et.onKeyDown(keyCode, event)*/
	        ImageButton searchButton = (ImageButton)findViewById(R.id.bazaaroid_search_button);
	        
	        searchButton.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	            	EditText et = (EditText)findViewById(R.id.bazaaroid_search_box);
	            	String query = et.getText().toString();
	            	doSearchAction(query);
	            }
	          });
	    } 
	    catch (Exception e) 
	    {
			// TODO Auto-generated catch block
			Log.e(TAG, e.getMessage());
		}
	}
	
	private void doSearchAction(String query)
	{
    	/*TextView mTextView = (TextView) findViewById(R.id.textField);
    	mTextView.setText(query);*/
		//Toast.makeText(CategoryView.this, query, Toast.LENGTH_SHORT).show();
		
		ArrayList<Product> searchResult = dbBazaaAdapter.doQueryProducts(query);
		ArrayList<String> searchResultString = new ArrayList<String>();
		
		for(int i = 0; i < searchResult.size(); ++i)
		{
			Log.d(TAG, String.format("%d: %s", i, searchResult.get(i).getName()));
			searchResultString.add(searchResult.get(i).getName() + " | " + searchResult.get(i).getDescription());
		}
		

	    Intent intent = new Intent(CategoryView.this, SearchResult.class);
	    //intent.putExtra("searchResult", searchResultString);\
	    intent.putExtra("query", query);
	    CategoryView.this.startActivity(intent);
	    
	    
	    /*
	    HttpClient client = new DefaultHttpClient();
	    //client.getParams()
	    
	    
		URI uri = null;
		
		try {
			uri = new URI("http://app.bazaaroid.com/");//("http://109.245.133.2:8888/");
		} catch (URISyntaxException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
        HttpGet httpGetRequest = new HttpGet(uri);// new HttpGet("http://109.245.133.2:8888/");//rest/search/products");//("http://10.98.81.225:8888/rest/v1/client"); 
        
        
        String line = "", responseString = "";
        try 
        {
        	HttpResponse response = client.execute(httpGetRequest);
        	
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			{
				BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				while ((line = br.readLine()) != null) 
				{
					responseString += line;
				}
				br.close();
			}
		} 
        catch (ClientProtocolException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e(TAG, String.format("Client protocol exception: %s", e.getMessage()));
		} 
        catch (IOException e) 
        {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e(TAG, String.format("I/O exception: %s", e.getMessage()));
		}	    
        
        Log.d(TAG, String.format("Response: %s", responseString));
        */
	}

}
